package com.aliyun.openservices.springboot.example.normal;

import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.SendResult;
import com.aliyun.openservices.ons.api.bean.ConsumerBean;
import com.aliyun.openservices.ons.api.bean.ProducerBean;
import com.aliyun.openservices.springboot.example.config.MqConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

/**
 * @author chengzhen
 * @date 2020/9/10
 * @time 5:58 PM
 */
@Service
public class NormalMessageStart {

    @Qualifier("buildConsumer")
    @Autowired
    private ConsumerBean consumer;
    @Autowired
    private ProducerBean producer;
    @Autowired
    private MqConfig mqConfig;

    public static int i = 0;

    @PostConstruct
    public void init(){
        //消费者在加载完组建以后启动
        System.out.println("消费者启动:....");
        consumer.start();
    }

    @Scheduled(cron = "0/5 * * * * ?")
    private void produceMsg(){
        producer.start();
        System.out.println("生产者启动:....");
        i++;
        Message msg = new Message(mqConfig.getTopic(), mqConfig.getTag(), ("Round:"+i).getBytes());
        String key = "keyis"+i;
        msg.setKey(key);
        SendResult sendResult = producer.send(msg);
        System.out.println("生产的第"+i+"条数据:"+sendResult.toString());
        producer.shutdown();
    }
}
